package edu.ncsu.csc.ip.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
import edu.ncsu.csc.ip.server.protocol.ProtocolServerImpl;

/**
 * Class <code></code>
 * 
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class ReceiverThread extends Thread {
	private DatagramPacket packet = null;
	private DatagramSocket socket = null;
	private ProtocolServerImpl protocol = null;
	private String filename = null;

	public ReceiverThread(DatagramSocket serverSocket, DatagramPacket receivePacket, String filename) {
		super("ServerThread");
		this.packet = receivePacket;
		this.socket = serverSocket;
		this.protocol = new ProtocolServerImpl(receivePacket);
		this.filename = filename;
	}

	public void run() {

		OutputStream out = null;
		byte [] data = Arrays.copyOfRange(packet.getData(), 8, packet.getData().length);
		
		if(protocol.removeNulls(data).length != 0){
			try {
				out = new FileOutputStream(new File(filename), true);
				out.write(protocol.removeNulls(data));
				out.close();
			} catch(IOException e) {
				e.printStackTrace();
			}
		}
		
		try {

			InetAddress IPAddress = packet.getAddress();
			int port = packet.getPort();
			byte [] ACK = protocol.makeACK(Arrays.copyOfRange(packet.getData(), 0, 4));
			DatagramPacket sendPacket = new DatagramPacket(ACK,
					ACK.length, IPAddress, port);
			socket.send(sendPacket);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
